'''
使用递归方式查找回文
'''

import sys


def openFile(file):
    try:
        # 保证代码块无论以怎样的方式结束都会自动关闭
        with open(file) as in_file:
            loadText = in_file.read().strip().split('\n')  # 读取文件内容，删除空格，并以'\n'分割
            loadText = [x.lower() for x in loadText]  # 列表推导:将一种列表或者可迭代对象转换成另一个列表的快速方法
            return loadText
    except IOError as e:
        print('文件{}打开发生{}错误'.format(file, e))
        sys.exit(1)


def Recursion(text):
    rev_text = text[::-1]
    end = len(text)
    #判定边界
    if end > 1 and text == rev_text:
        return True
    if text[0] != text[-1]:
        return False
    return Recursion(text[1:-1])

if __name__ == '__main__':
    WordList = openFile('2of4brif.txt')

    PaliList = []  # 存放回文单词

    WordLists = set(WordList)

    for word in WordLists:
        is_true = Recursion(word)
        if is_true == True:
            PaliList.append(word)

    pali_sorted = sorted(PaliList)

    print('一共发现{}个回文单词'.format(len(pali_sorted)), file=sys.stderr)
    print(*pali_sorted,sep='\n')